<?php
namespace control;
/*
*离职记录类
*/

class staffQuitRecordClass extends adIndexClass
{
    private const page = 'staffQuitRecord';
    private const table = 'staff_quit_record';
    private const title = '离职记录';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "姓名"     => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    '部门' => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                ],
                [
                    '职位'   => selectMultiple(["name" => "jobId", 'table' => " job", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                    "预计离职日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $url = root . "control/adIndex.html?cla=" . self::page;
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => '单据编号',
                        'width' => 200,
                    ],
                    'name' => [
                        'name'  => '姓名',
                        'width' => 150,
                    ],
                    'department'  => [
                        'name'  => '部门',
                        'width' => 150,
                    ],
                    'job'         => [
                        'name'  => '职位',
                        'width' => 200,
                    ],
                    'type'          => [
                        'name'  => '离职类别',
                        'width' => 200,
                    ],
                    'quitDate'          => [
                        'name'  => '预计离职日期',
                        'width' => 200,
                    ],
                    'handStid'          => [
                        'name'  => '交接人',
                        'width' => 200,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 250,
                    ],
                ];
        }
        return $tr;
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//编号
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "staffId" => $this->post('stid'),//姓名
            "jobId" => $this->post('jobId'),//职位
        );
        $and = $this->seeSelf(self::page);
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and jobId in (select id from job where departmentId = '{$this->post('departmentId')}')";
        }
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'quitDate');
        }
        //排序
        $orderBy = $this->orderBy(array(
            "search" => $this->post('orderBy') ?? null,
            "default" => "单据编号降序",
            "array" => array(
                "orderNo" => array("desc" => "单据编号降序"),
            ),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取表头
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => $array['state']=='草稿'?array("title" => self::title . "详情", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"):[],
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $job = query('job', " id = '$array[jobId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "name":
                        $talent_pool = query('talent_pool'," id = '$array[talentId]'");
                        $row[] = $talent_pool['name'];
                        break;
                    case "department":
                        $department = query('department', " id = '$job[departmentId]'");
                        $row[] = $department['name'];
                        break;
                    case "job":
                        $row[] = $job['name'];
                        break;
                    case "handStid":
                        $row[] = self::findStaff($array['handStid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => [],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id =  $this->post('id');
        $info = query(self::table, " id = '" .$id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "姓名：" => selectMultiple(["name" => "staffId", 'table' => "staff", 'where' => "state !='离职' and stid not in (select stid from user where isDel = 1)", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '姓名', "value" => $info['staffId']]),
                    must . "离职类别：" => select(["name" => "type", 'title' => '离职类别', 'option' => explode('，', para('quitType')), 'class' => 'text', "value" => $info['type']]),
                ],
                [
                    must . "预计离职日期：" => text(["name" => "quitDate", 'laydate' => [], 'class' => 'select', "value" => $info['quitDate']]),
                    must . "离职原因：" => select(["name" => "reason", 'title' => '请选择', 'option' => explode('，', para('reasonOption')), 'class' => 'text', "value" => $info['reason']]),
                ],
                [
                    "交接人：" => selectMultiple(["name" => "handStid", 'table' => "staff", 'where' => "state !='离职'", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '请选择', "value" => $info['handStid']]),
                ],
                [
                    "详细说明：" => textarea(array('name' => 'description', 'value' => $info['description'])),
                ],
                [
                    "附件：" => fileUploadClass::addFileComponent($info['id'], '离职记录', self::page, self::page . 'EditForm'),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }


    public function listEdit()
    {
        $id = $this->post('id');
        $field = [
            'listItem' => $this->post('listItem') ? json_encode($this->post('listItem'), 320) : json_encode([], 320),
        ];
        $info = query(self::table, "id = '$id'");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($id)) {
            $json['warn'] = '未找到ID';
        }/* elseif ($info['state'] != '草稿') {
            $json['warn'] = '不是草稿状态，不能编辑';
        } */else {
            $json['warn'] = static::update([
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$id'"
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "的离职事项清单， 离职记录id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //附件
        $fileIdArr = $this->post('fileId');
        $field = [
            'staffId' => $this->post('staffId'),
            'handStid' => $this->post('handStid'),
            'type' => $this->post('type'),
            'quitDate' => $this->post('quitDate'),
            'reason' => $this->post('reason'),
            'description' => $this->post('description')
        ];
        $annotation = [
            'staffId' => '姓名',
            'type' => '离职类型',
            'quitDate' => '预计离职日期',
            'reason' => '离职原因',
        ];
        $rules = [
            'staffId' => 'required',
            'type' => 'required',
            'quitDate' => 'required',
            'reason' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $staff = query('staff', " stid = '$field[staffId]'");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        }elseif($field['staffId'] == $field['handStid']){
            $json['warn'] = '离职人员和交接人不能相同';
        } else {
            $field['jobId'] = $staff['jobId'];
            $where = " id = '$id' ";
            $staff = query('staff', " stid = '$field[staffId]'");
            $field['talentId'] = $staff['talentId'];
            $info = query(self::table, $where);
            if (!$info['id']) {
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'LZSQ' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'deptName' => $department['name'],
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加主表ID到附件表
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '离职申请',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿' && $info['isConfirm'] != 1) {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );
            $talent_pool = query('talent_pool', " id = '$info[talentId]'");
            $job = query('job', " id = '$info[jobId]'");
            $department = query('department', " id = '$job[departmentId]'");
            $entry = query('staff_entry_record', " talentId = '$info[talentId]'  order by time desc");
            //审核按钮
            $button = $this->auditButton($info);
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                ];
                $button[] = [
                    "name" => "上传离职证明",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "uploadFile",
                    "post" => ["id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            if ($this->power(self::page, 'confirm') && $info['state'] == '已通过' && !$info['isConfirm']) {
                //按钮
                $button[] = [
                    "name" => "确认离职",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "confirmOut",
                    "post" => ["id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }

            $audit = query('audit', " targetId = '$info[id]'");
            $listArr = $info['listItem'] ? json_decode($info['listItem'], true) : [];
            $quitList = explode('，', para('quitOption'));
            $li = "<ul class='quit-item'>";
            foreach ($quitList as $val) {
                $checked = "";
                if (in_array($val, $listArr)) {
                    $checked = "checked";
                }
                $li .= "<li><label class='checkbox'><input name='listItem[]' value='$val' $checked type='checkbox'><span></span>&nbsp;$val</label></li>";
            }
            $li .= "</ul>";
            $endDate = $this->date;
            $tr[] = ['领用日期', '物品名称', '规格型号', '编码', '资产残值（元）', '备注'];
            $all = find(array('table' => 'asset_use', 'where' => "receiver = '$info[staffId]' and state = '已通过' order by receivingDate"));
            $total_tr = [4=>0];
            foreach ($all['array'] as $array) {
                $childArr = find(array('table' => 'asset_use_detail', "where" => "orderId = '$array[id]'"));
                foreach ($childArr['array'] as $val) {
                    $asset = query('asset', "id = '$val[atid]'");
                    $ratio = assetManagementClass::monthRatio($asset['depreciationMethod'],$asset['discountYear'],$asset['money'],$asset['purchaseMoney'],$asset['depreciationMoney'],$asset['purchaseDate'],$endDate,1);
                    $monthDecMoney =assetManagementClass::monthDecMoney($asset['depreciationMethod'],$asset['purchaseMoney'],$ratio/100,$asset['purchaseDate'],$endDate,$asset['discountYear'],$asset['money'],$asset['depreciationMoney']);
                    $discountMoney = assetManagementClass::calcSalvage($asset['depreciationMethod'],$monthDecMoney,$asset['purchaseDate'],$asset['discountYear'],$asset['purchaseMoney'],$asset['money'],$asset['depreciationMoney'],$endDate);
                    $salvage = round($asset['purchaseMoney']-$discountMoney,2);
                    $tr[] = [$array['receivingDate'], $asset['name'], $asset['model'], $asset['orderNo'], $salvage, $val['text']];
                }
                $total_tr[4] += $salvage;
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "姓名" => $talent_pool['name'],
                        "部门" => $department['name'],
                        "职位" => $job['name'],
                        "入职日期" => $entry['entryDate'],
                    ),
                    array(
                        "离职类别" => $info['type'],
                        "预计日期" => $info['quitDate'],
                        "交接人"=>self::findStaff($info['handStid']),
                        "离职原因" => $info['reason'],
                    ),
                    array(
                        "详细说明" => pre($info['description']),
                    ),
                ),
                '离职事项清单' => array(
                    array(
                        "<form name='detailForm'>$li<input name='id' value='$info[id]' type='hidden'></form>"
                    )
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '物品领用记录',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'showSort' => true, 'total' => $total_tr)),
            ]);
            $data['html']   .= $this->tableShow(array(
                '附件' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '离职记录')
                    )
                ),
                '离职证明' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '离职证明')
                    )
                ),
                '系统信息' => array(
                    array(
                        "单据编号" => $info['orderNo'],
                        "申请人部门" => $info['deptName'],
                        "申请人" => self::findStaff($info['stid']),
                    ),
                    array(
                        "创建时间" => $info['time'],
                        "提交时间" => self::null($audit['commitTime']),
                        "状态" => $info['state'],
                    ),
                ),
                '流程' => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id'])
                    )
                ),
            ));
            $data['html'] .= <<<eof
               <style>
               .quit-item li{margin: 5px 0}
                </style>
                <script>
                $(".quit-item input[type='checkbox']").on('click',function(res) {
                   subForm('detailForm',root+'control/adIndex.html?cla=staffQuitRecord&fun=listEdit')
                })
                </script>
eof;

            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    public function uploadFile()
    {
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    fileUploadClass::addFileComponent($this->post('id'), '离职证明', self::page, 'staffQuitRecordUploadFileForm')
                ),
            )
        ));
        //返回
        return $this->layer(array("title" => "上传离职证明", "height" => 300, "width" => 900, "html" => $html));
    }

    public function uploadFileEdit(): bool|string
    {
        $fileIdArr = $this->post('fileId')?:[];
        $id = $this->post('id');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($id)) {
            $json['warn'] = '未找到ID';
        } else {
            $warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
            if (in_array($warn, ['新增成功', '更新成功'])) {
                $json['warn'] = 2;
                $_SESSION['warn'] = '上传成功';
            } else {
                $json['warn'] = '上传失败';
            }
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';

                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 确认
     */
    public function confirmOut(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "日期：" => text(array('name' => 'chooseDate', 'laydate' => [], 'value' => $this->date)),
            ),
        )
        ));
        //返回
        return $this->layer(array("title" => "确认", "height" => 200, 'width' => 500, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     *确认离职
     */
    public function confirmOutEdit(): bool|string
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $chooseDate = $this->post('chooseDate');
        if (!$this->power(self::page, "confirm")) {
            $json['warn'] = "你没有" . self::title . "的确认权限";
        } elseif (empty($info['id'])) {
            $json['warn'] = "未找到此" . self::title;
        } elseif ($info['state'] != '已通过') {
            $json['warn'] = '此申请还未审核通过';
        } elseif (empty($chooseDate)) {
            $json['warn'] = '请选择确认日期';
        } else {
            $staff = query('staff', " stid = '$info[staffId]'");
            $entry = query('staff_entry_record', "talentId = '$staff[talentId]' and id not in (select talentId from staff_quit_record where staffId = '$staff[stid]') order by time desc");
            $this->startTrans();
            $field = [
                'isConfirm' => 1,
                'confirmDate' => $chooseDate,
                'entryId' => $entry['id']
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id ='$id'"));
            //修改员工表状态
            $bool = static::update(array('table' => 'staff', 'field' => ['quitDay' => $this->date, 'state' => '离职'], 'where' => " stid ='$info[staffId]'"));
            if ($bool != '更新成功') {
                $json['warn'] = '修改员工离职状态失败';
            }
            //修改人才库状态 以便可以再次申请入职
            $bool = static::update(array('table' => 'talent_pool', 'field' => ['workFlow' => 0], 'where' => " id ='$staff[talentId]'"));
            if ($bool != '更新成功') {
                $json['warn'] = '修改人才库状态失败';
            }
            //修改参保信息为待停保
            $bool = static::update(array('table' => 'staff_insure', 'field' => ['workFlow' => '待停保'], 'where' => " staffId ='$staff[stid]' and workFlow !='已停保'"));
            if ($bool != '更新成功') {
                $json['warn'] = '修改参保状态失败';
            }
            //修改合同状态
            $staff_contract = query('staff_contract',"staffId = '$staff[stid]' and workFlow = '生效中'");
            if (strtotime($chooseDate) >= strtotime($staff_contract['signEndDate'])){
                $bool = static::update(array('table' => 'staff_contract', 'field' => ['workFlow' => '已终止','isQuit'=>1], 'where' => " id = '$staff_contract[id]'"));
            }else{
                $bool = static::update(array('table' => 'staff_contract', 'field' => ['workFlow' => '已解除','isQuit'=>1], 'where' => " id = '$staff_contract[id]'"));
            }
            $bool2 = static::update(array('table' => 'staff_contract', 'field' => ['isQuit'=>1], 'where' => " staffId = '$staff[stid]' and isClose = 0 and workFlow = '已终止'"));
            if ($bool != '更新成功' || $bool2 !='更新成功') {
                $json['warn'] = '修改合同状态失败';
            }
            //修改此人直属下级的直接上级人员
            $bool = static::update(array('table' => 'staff', 'field' => ['manager' => $info['handStid']], 'where' => " manager = '$info[staffId]'"));
            if ($bool !='更新成功'){
                $json['warn'] = '修改直接上级失败';
            }
            //修改审批
            $all = find(['table' => 'examine', 'where' => "staff like '%" . $info['staffId'] . "%' or conditions like '%" . $info['staffId'] . "%' or node like '%" . $info['staffId'] . "%'"]);
            foreach ($all['array'] as $array) {
                $staffStr = str_replace($info['staffId'], $info['handStid'], $array['staff']);
                $conditions = str_replace($info['staffId'], $info['handStid'], $array['conditions']);
                $node = str_replace($info['staffId'], $info['handStid'], $array['node']);
                update(array('table' => 'examine', 'field' => array('staff' => $staffStr, 'conditions' => $conditions, 'node' => $node), 'where' => " id = '$array[id]'"));
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //生成员工变动记录
                $obj = new staffEntryRecordClass();
                $obj->insertStaffStateRecord($info['staffId'], '离职', $info['id'], $this->date);
                //添加日志
                $text = $this->control['name'] . "确认了" . self::title . "， id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            } else {
                $this->rollback();
            }
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    fileClass::deleteFile($id);
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}

